using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Lizk.Media
{

    public class SimpleEventWorker
    {
        private class Job
        {
            public WaitCallback Method { get; set; }
            public object Payload { get; set; }
            
            public Job(WaitCallback method, object payload)
            {
                this.Method = method;
                this.Payload = payload;
            }
        }

        Queue<Job> queue = new Queue<Job>();
        
        Thread worker;

        public void Enqueue(WaitCallback handler, object payload)
        {
            lock (queue)
            {
                queue.Enqueue(new Job(handler, payload));
                Monitor.PulseAll(queue);
            }
            StartThread();
        }

        private void ProcessQueue()
        {
            while (true)
            {
                Job job;
                lock (queue)
                {
                    while (queue.Count == 0)
                        Monitor.Wait(queue);
                    job = queue.Dequeue();
                }
                job.Method(job.Payload);
            }
        }

        public ThreadState State
        {
            get {
                if (worker == null)
                    return ThreadState.Stopped;
                else
                    return worker.ThreadState;
            }
        }

        private void StartThread()
        {
            if (worker == null || worker.ThreadState == ThreadState.Stopped)
            {
                worker = new Thread(new ThreadStart(ProcessQueue));
                worker.IsBackground = true;
                worker.Start();
            }
        }

        ~SimpleEventWorker() { Kill(); }

        public void Kill()
        {
            if(worker != null)
                worker.Abort();
            worker = null;
        }
    }

}
